package action;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import dao.ProductDao;
import po.Product;
import service.WholesalerService;
import util.PathTool;

/**
 * Servlet implementation class PurchaseServlet
 */
@WebServlet("/PurchaseServlet")
public class PurchaseServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public PurchaseServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		if (session.getAttribute("login") != null && (boolean)session.getAttribute("login")) {
			Product p = new Product();
			p.setName(request.getParameter("name"));
			p.setPrice(Integer.valueOf(request.getParameter("price")));
			p.setInfo(request.getParameter("info"));
			p.setid(String.valueOf(ProductDao.getRecordAmount()));
			// 写入商品数据库
			WholesalerService.wholesale(p);
			response.getWriter().write("sussess. <br/> <a href=\""
					+ request.getHeader("Referer")
					+ "\">&nbsp;&nbsp;&nbsp;Return</a>");
		} else {
			String message = "<a href=\"./"
					+ PathTool.getFileName(request.getHeader("Referer"))
					+ "\">&nbsp;&nbsp;&nbsp;Return</a>";
			response.getWriter().write("not login. <br/>" + message);
			System.out.println(PathTool.getFileName(request.getHeader("Referer")));
		}
	}

}
